﻿using MongoDB.Driver;
using Sustainalytics.ESG.Entities;
using Sustainalytics.ScreeningTool.Synchronization.Caches;
using System.Collections.Generic;
using System.Linq;

namespace Sustainalytics.ScreeningTool.Synchronization.Handlers.ESG
{
    public class CompanyKeyESGIssueHandler : IHandler<CompanyKeyESGIssue>
    {
        private readonly ResearchStatesCache _researchStatesCache;

        public CompanyKeyESGIssueHandler(ResearchStatesCache researchStatesCache)
        {
            _researchStatesCache = researchStatesCache;
        }

        public ProjectionDefinition<CompanyKeyESGIssue> GetProjection(ProjectionDefinitionBuilder<CompanyKeyESGIssue> builder) => builder
            .Include("KeyESGIssues.SortKey")
            .Include("KeyESGIssues.Name")
            .Include("KeyESGIssues.Comment");

        public IEnumerable<ExtraElement> GetExtraElements(CompanyKeyESGIssue entity)
        {
            if (!_researchStatesCache.IsResearchAvailable(entity.Id, x => x.ComprehensiveEsg))
                return new ExtraElementList();

            return entity.KeyESGIssues.OrderBy(x => x.SortKey?.Value).Take(3).SelectMany((x, i) =>
            {
                var key = $"Key ESG Issue {i + 1}";
                return new ExtraElementList
                {
                    { $"{key}-Name",    x.Name    },
                    { $"{key}-Summary", x.Comment },
                };
            });
        }
    }
}
